﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Hosting;
using EPiBoost.Core.Interfaces.ContentInterfaces;
using EPiServer;
using EPiServer.Core;
using EPiServer.SpecializedProperties;
using EPiServer.Web;
using EPiServer.Web.Hosting;

namespace EPiBoost.Core.Extensions
{
	public static class LinkItemExtensions
	{
		public static string GetMainTitle(this LinkItem linkItem)
		{
			var epiServerpage = linkItem.GetPage() as IMainTitle;
			if(epiServerpage!=null)
			{
				return epiServerpage.MainTitle;
			}
			return linkItem.Text;
		}
		
		public static PageData GetPage(this LinkItem linkItem)
		{
			PageData result;
			TryParseToPageData(linkItem, out result);
			return result;
		}
		

		public static bool TryParseToPageData(this LinkItem self, out PageData result)
		{
			return self.TryParseToPageData(out result, null);
		}

		/// <summary>
		/// Tries to parse a LinkItem to a PageData object
		/// </summary>
		/// <param name="self">LinkItem object</param>
		/// <param name="result">The PageData object if it can be parsed - otherwise null</param>
		/// <param name="languageBranch">The language code to return page data's from</param>
		/// <returns>If the LinkItem can be parsed to PageData</returns>
		public static bool TryParseToPageData(this LinkItem self, out PageData result, string languageBranch)
		{
			result = null;

			Guid guid = PermanentLinkUtility.GetGuid(self.Href);

			if (guid == Guid.Empty)
			{
				return false;
			}
			else
			{
				try
				{
					PageReference pRef = PermanentLinkUtility.FindPageReference(guid);
					if (languageBranch != null)
					{
						result = DataFactory.Instance.GetPage(pRef, new LanguageSelector(languageBranch));
						if (result == null)
							return false;
					}
					else
					{
						result = DataFactory.Instance.GetPage(pRef);
					}
					return true;
				}
				catch (Exception)
				{
					return false;
				}
			}
		}

		public static bool TryParseToUnifiedFile(this LinkItem self, out UnifiedFile result)
		{
			return TryParseToUnifiedFile(self.Href, out result);
		}

		public static bool TryParseToUnifiedFile(string linkUrl, out UnifiedFile result)
		{
			result = null;

			string virtualPath;
			if (PermanentLinkMapStore.TryToMapped(linkUrl, out virtualPath))
			{
				try
				{
					result = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath) as UnifiedFile;

					if (result != null)
					{
						return true;
					}
				}
				catch
				{
					return false;
				}
			}

			return false;
		}
	}
}
